from flask import Blueprint, request, current_app
from models.models import Device, db
from utils.helpers import api_response, process_image

device_bp = Blueprint('device', __name__)

@device_bp.route('', methods=['POST'])
def create_device():
    """
    创建新设备
    ---
    tags:
      - 设备管理
    parameters:
      - name: body
        in: body
        required: true
        schema:
          type: object
          required:
            - device_id
            - device_name
          properties:
            device_id:
              type: string
              description: 设备唯一标识
            device_name:
              type: string
              description: 设备名称
            device_type:
              type: string
              description: 设备类型
            device_status:
              type: string
              description: 设备状态
              default: active
            device_info:
              type: string
              description: 设备附加信息
            image:
              type: string
              description: 设备图片的Base64编码
            device_web:
              type: string
              description: 设备Web页面地址
    responses:
      201:
        description: 设备创建成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 201
            message:
              type: string
              example: "设备创建成功"
            data:
              type: object
              properties:
                id:
                  type: string
                  description: 设备ID
                name:
                  type: string
                  description: 设备名称
                image:
                  type: string
                  description: 设备图片路径
      400:
        description: 参数错误
      500:
        description: 服务器内部错误
    """
    data = request.json
    required_fields = ['device_id', 'device_name']
    if not all(field in data for field in required_fields):
        return api_response(message="缺少必要字段", code=400, status_code=400)
        
    if Device.query.get(data['device_id']):
        return api_response(message="设备ID已存在", code=400, status_code=400)
        
    try:
        new_device = Device(
            device_id=data['device_id'],
            device_name=data['device_name'],
            device_type=data.get('device_type'),
            device_status=data.get('device_status', 'active'),
            device_info=data.get('device_info'),
            device_web=data.get('device_web')
        )
        
        if data.get('image'):
            new_device.img_path = process_image(current_app, data['image'], 'device')
            
        db.session.add(new_device)
        db.session.commit()
        
        return api_response(
            data={
                "id": new_device.device_id,
                "name": new_device.device_name,
                "image": new_device.img_path
            },
            message="设备创建成功",
            code=201,
            status_code=201
        )
    except Exception as e:
        db.session.rollback()
        return api_response(message=str(e), code=500, status_code=500)

@device_bp.route('/', methods=['GET'])
def get_all_devices():
    """
    获取所有设备列表
    ---
    responses:
      200:
        description: 成功返回设备列表
        schema:
          type: array
          items:
            properties:
              id:
                type: string
                description: 设备ID
              name:
                type: string
                description: 设备名称
              status:
                type: string
                description: 设备状态
    """
    try:
        devices = Device.query.all()
        return api_response(
            data=[{
                "id": d.device_id,
                "name": d.device_name,
                "type": d.device_type,
                "status": d.device_status,
                "image": d.img_path
            } for d in devices],
            code=200
        )
    except Exception as e:
        return api_response(message=str(e), code=500, status_code=500)

@device_bp.route('/<device_id>', methods=['GET'])
def get_device(device_id):
    """
    获取设备详情
    ---
    tags:
      - 设备管理
    parameters:
      - name: device_id
        in: path
        type: string
        required: true
        description: 设备ID
    responses:
      200:
        description: 获取成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            data:
              type: object
              properties:
                device_id:
                  type: string
                  description: 设备ID
                name:
                  type: string
                  description: 设备名称
                type:
                  type: string
                  description: 设备类型
                status:
                  type: string
                  description: 设备状态
                image:
                  type: string
                  description: 设备图片路径
                info:
                  type: string
                  description: 设备信息
                web_info:
                  type: string
                  description: 设备Web信息
                create_time:
                  type: string
                  description: 创建时间
      404:
        description: 设备不存在
      500:
        description: 服务器内部错误
    """
    try:
        device = Device.query.get(device_id)
        if not device:
            return api_response(message="设备不存在", code=404, status_code=404)
            
        return api_response(
            data={
                "device_id": device.device_id,
                "name": device.device_name,
                "type": device.device_type,
                "status": device.device_status,
                "image": device.img_path,
                "info": device.device_info,
                "web_info": device.device_web,
                "create_time": device.time.isoformat()
            },
            code=200
        )
    except Exception as e:
        return api_response(message=str(e), code=500, status_code=500)

@device_bp.route('/<device_id>', methods=['DELETE'])
def delete_device(device_id):
    """
    删除设备
    ---
    tags:
      - 设备管理
    parameters:
      - name: device_id
        in: path
        type: string
        required: true
        description: 设备ID
    responses:
      200:
        description: 删除成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: "设备已删除"
      404:
        description: 设备不存在
      500:
        description: 服务器内部错误
    """
    try:
        device = Device.query.get(device_id)
        if not device:
            return api_response(message="设备不存在", code=404, status_code=404)
            
        db.session.delete(device)
        db.session.commit()
        
        return api_response(message="设备已删除", code=200)
    except Exception as e:
        db.session.rollback()
        return api_response(message=str(e), code=500, status_code=500) 